import pubsub, { ROUTER_BEFOREEACH, ROUTER_AFTEREACH, ROUTER_ERROR } from '@/utils/pubsub';
import { RouteLocationNormalizedGeneric, RouteLocationNormalizedLoadedGeneric, Router } from 'vue-router';

const intercept = (router: Router) => {
    pubsub.on(ROUTER_BEFOREEACH, (to: RouteLocationNormalizedGeneric, from: RouteLocationNormalizedLoadedGeneric) => {
        // dosomething before each route
        console.log('beforeEach', to, from);
        return true;
    });
    pubsub.on(ROUTER_AFTEREACH, (to: RouteLocationNormalizedGeneric, from: RouteLocationNormalizedLoadedGeneric) => {
        // dosomething after each route
        console.log('afterEach', to, from);
    })
    pubsub.on(ROUTER_ERROR, (error: any) => {
        // dosomething when route error
        console.log('error', error);
    })
  // 路由进入前
  router.beforeEach((to, from, next) => {
    const result = pubsub.emit(ROUTER_BEFOREEACH, to, from);
    if (!result || result.some((item) => item === false)) {
      next(false);
    } else {
      next();
    }
  });
  // 路由进入后
  router.afterEach((to, from) => {
    pubsub.emit(ROUTER_AFTEREACH, to, from);
  })
  // 路由错误
  router.onError((error) => {
    pubsub.emit(ROUTER_ERROR, error);
  })
}

export default intercept;
